package cn.cdeden.knowledge.controller.team;

import cn.cdeden.common.core.utils.MapstructUtils;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.knowledge.domain.Team;
import cn.cdeden.knowledge.domain.TeamRole;
import cn.cdeden.knowledge.domain.dto.TeamMemberDto;
import cn.cdeden.knowledge.domain.dto.TeamRoleDto;
import cn.cdeden.knowledge.domain.dto.TeamRoleQueryParam;
import cn.cdeden.knowledge.enums.TeamTypeEnum;
import cn.cdeden.knowledge.service.TeamMemberService;
import cn.cdeden.knowledge.service.TeamRoleService;
import cn.cdeden.knowledge.service.TeamService;
import cn.cdeden.system.api.model.LoginUser;
import com.alibaba.fastjson.JSONArray;
import cn.cdeden.common.core.domain.R;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Chen
 * @date 2022-11-22
 **/
@RestController
@Controller
@RequiredArgsConstructor
//@Api(tags = "团队文档权限角色管理")
@RequestMapping("/api/teamRole")
public class TeamRoleController {

    private final TeamRoleService teamRoleService;

    private final TeamMemberService teamMemberService;

    private final TeamService teamService;

//    @Log("查询团队文档权限角色")
//    @ApiOperation("查询团队文档查询权限角色")
    @GetMapping(value = "/query")
    @ResponseBody
    public R query(TeamRoleQueryParam query, Pageable pageable) {
        TableDataInfo<TeamRoleDto> teamPermDtoPageInfo = teamRoleService.queryAll(query, pageable);
        return R.ok(teamPermDtoPageInfo);
    }

//    @Log("新增团队文档权限角色")
//    @ApiOperation("新增团队文档权限角色")
    @PostMapping(value = "/add")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public R add(@RequestBody TeamRoleDto teamRoleDto) {
        String teamId = teamRoleDto.getTeamId();
        Team team = teamService.getById(teamId);
        if (team.getType().equals(TeamTypeEnum.PROJECT_TEAM.getNum())){
            return R.fail("项目团队：“" + team.getTeamName() +"“ 不可修改");
        }
        LoginUser user = LoginHelper.getLoginUser();

        //判断是否有同名
        TeamRoleQueryParam query = new TeamRoleQueryParam();
        query.setTeamId(teamRoleDto.getTeamId());
        List<TeamRoleDto> teamRoleDtoList = teamRoleService.queryAll(query);
        for (TeamRoleDto roleDto : teamRoleDtoList) {
            if (roleDto.getRoleName().equals(teamRoleDto.getRoleName())){
                throw new RuntimeException("已有同名角色！");
            }
        }
        haveMemberRole(teamRoleDto, user);
        teamRoleDto.setParams(JSONArray.toJSONString(teamRoleDto.getPermCodes()));
        teamRoleService.insert(teamRoleDto);
        return R.ok(null);
    }

//    @Log("修改团队文档角色")
//    @ApiOperation("修改团队文档角色")
    @PostMapping(value = "/updateUserRoleType")
    @Transactional(rollbackFor = Exception.class)
    public R updateUserRoleType(@RequestBody TeamRoleDto teamRoleDto) {

        String teamId = teamRoleDto.getTeamId();
        Team team = teamService.getById(teamId);
        if (team.getType().equals(TeamTypeEnum.PROJECT_TEAM.getNum())){
            return R.fail("项目团队：“" + team.getTeamName() +"“ 不可修改");
        }

        LoginUser user = LoginHelper.getLoginUser();
        haveMemberRole(teamRoleDto, user);
        teamRoleDto.setParams(JSONArray.toJSONString(teamRoleDto.getPermCodes()));
        teamRoleService.updateRole(teamRoleDto);
        return R.ok(null);
    }

//    @Log("删除团队成员角色")
//    @ApiOperation("删除团队成员角色")
    @PostMapping(value = "/delete")
    @Transactional(rollbackFor = Exception.class)
    public R delete(@RequestBody String id) {
        LoginUser user = LoginHelper.getLoginUser();
        TeamRole teamRole = teamRoleService.getById(id);
        Team team = teamService.getById(teamRole.getTeamId());
        if (team.getType().equals(TeamTypeEnum.PROJECT_TEAM.getNum())){
            return R.fail("项目团队：“" + team.getTeamName() +"“ 不可修改");
        }
        if (id.equals(team.getDefaultRole())){
            //删除的是默认角色 清空默认角色
            team.setDefaultRole(null);
            teamService.updateById(team);
        }
        //将删除的角色
        TeamRoleDto teamRoleDto = MapstructUtils.convert(teamRole, TeamRoleDto.class);
        haveMemberRole(teamRoleDto,user);
        List<TeamMemberDto> list = teamMemberService.getByRoleId(teamRoleDto.getId());
        if (list.size() > 0){
            throw new RuntimeException("团队中有此角色成员！");
        }
        return R.ok(teamRoleService.removeById(id));
    }

    private void haveMemberRole(@RequestBody TeamRoleDto teamRoleDto, LoginUser user) {
        List<TeamMemberDto> role = teamMemberService.getRole(teamRoleDto.getTeamId(), user);
        for (TeamMemberDto teamMemberDto : role) {
            if (teamMemberDto.getId() == null) {
                throw new RuntimeException("无权限！");
            }
            TeamRole teamRole = teamRoleService.getById(teamMemberDto.getRoleId());
            if (teamRole.getRank() != 1) {
                throw new RuntimeException("仅最高等级角色可操作团队角色！");
            }
        }

    }

}
